//
//  PinJieContentScrollView.m
//  PingTu
//
//  Created by Yangfan on 15/2/11.
//  Copyright (c) 2015年 4gread. All rights reserved.
//

#import "PinJieContentScrollView.h"
#import <UIImage+Resize.h>

@implementation PinJieContentScrollView

-(id)initWithFrame:(CGRect)frame {
    if (self=[super initWithFrame:frame]) {
        [self setShowsVerticalScrollIndicator:NO];
    }
    return self;
}

- (void)setAssetsToImageArr:(NSArray *)assets {
    _assets = assets;
    
    // 初始化
    if (imageArr == nil) {
        imageArr = [[NSMutableArray alloc] init];
    }
    if (imageRectArr == nil) {
        imageRectArr = [[NSMutableArray alloc] init];
    }
    for (int i = 0; i < _assets.count; i++) {
        ALAsset *asset = [_assets objectAtIndex:i];
        [imageArr addObject:[UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage]];
    }
}

// 开始布局
- (void)createAndUpdateUI:(int)which andDic:(NSDictionary *)dic {
    [self setWhichMuBanAndDic:which andDic:dic];
//    [self setContentOffset:CGPointMake(0, 0)];
//    for (UIView *view in [self subviews]) {
//        [view removeFromSuperview];
//    }
    
    [self updateHeaderAndBackgroundColor:which andDic:dic];
    
    // 所有的图片都在这个view上面
    if (allImageView != nil) {
        [allImageView removeFromSuperview];
    }
    allImageView = [[UIView alloc] init];
    [self addSubview:allImageView];
    
    UIImageView *oneImageView;
    UIImage *oneImage;
    CGSize oneImageSize = CGSizeZero;
    float oneImageWidth = self.frame.size.width - 14;
    contentHeight = 0;
    // 把尺寸数组中的数据清空
    [imageRectArr removeAllObjects];
    for (int i = 0; i < imageArr.count; i++) {
        oneImage = [imageArr objectAtIndex:i];
        oneImageView = [[UIImageView alloc] initWithImage:oneImage];
        [oneImageView setTag:i];
        [oneImageView setUserInteractionEnabled:YES];
        [oneImageView setContentMode:UIViewContentModeScaleToFill];
        oneImageSize = [self returnNowSizeWithOriginSize:CGSizeMake(oneImage.size.width, oneImage.size.height) andWantWidth:oneImageWidth];
        [oneImageView setFrame:CGRectMake(7, contentHeight, oneImageSize.width, oneImageSize.height)];
        [allImageView addSubview:oneImageView];
        
        // 把图片的Rect值记录在数组中
        [imageRectArr addObject:[self rectToString:oneImageView.frame]];
        
        contentHeight += oneImageSize.height + 7;
        
        // 为图片添加拖动的手势（为了拖动改变图片位置）
        UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pinjiehandlePan:)];
        panRecognizer.delegate = self;
        [oneImageView addGestureRecognizer:panRecognizer];
        
        UILongPressGestureRecognizer * longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(pinjielongPressToDo:)];
        longPressGr.minimumPressDuration = 0.3;
        [oneImageView addGestureRecognizer:longPressGr];
    }
    
    contentHeight -= 7;
    [allImageView setFrame:CGRectMake(0, headerHeight, self.frame.size.width, contentHeight)];
    
    [self updateFooter:which andDic:dic];
    [self bringSubviewToFront:allImageView];// 将图片视图层调整到屏幕最上面
}

// 长按手势
- (void)pinjielongPressToDo:(UILongPressGestureRecognizer *)recognizer {
    UIImageView *currentPlusImage = (UIImageView *)recognizer.self.view;
    if (recognizer.state == UIGestureRecognizerStateEnded) {
        _isStarDrag = NO;
        currentPlusImage.layer.borderWidth = 0;
        [self setContentOffset:originPoint animated:YES];
        [self setScrollEnabled:YES];
        
        CGPoint point = [recognizer locationInView:allImageView];
        for (int i = 0; i < imageRectArr.count; i++) {
            if (i == currentPlusImage.tag) {
                if (i == imageRectArr.count - 1) {
                    [currentPlusImage setFrame:originRect];
                }
                continue;
            }
            
            if ([self returnRectIsContainCGPoint:[self stringToRect:[imageRectArr objectAtIndex:i]] andPoint:point]) {
                NSLog(@"YES");
                
                // 图片数组中交换两个图片的位置
                [imageArr exchangeObjectAtIndex:currentPlusImage.tag withObjectAtIndex:i];
                // 图片转换位置
                [self createAndUpdateUI:whichYangShi andDic:dicFromPrePage];
                break;
            }
            if (i == imageRectArr.count - 1) {
                [currentPlusImage setFrame:originRect];
            }
        }
        
        
    } else if(recognizer.state == UIGestureRecognizerStateBegan) {
        _isStarDrag = YES;
        currentPlusImage.layer.borderColor = [[UIColor redColor] CGColor];
        currentPlusImage.layer.borderWidth = 3;
        
        [allImageView bringSubviewToFront:currentPlusImage];
        
        originRect = [currentPlusImage frame];
//        [self setContentSize:CGSizeMake(self.frame.size.width, self.frame.size.height)];
        // 记录当前的滚动地方
        originPoint = [self contentOffset];
        [self setScrollEnabled:NO];
    }
}

// 拖动手势
- (void)pinjiehandlePan:(UIPanGestureRecognizer *)recognizer {
//    UIImageView *currentPlusImage = (UIImageView *)recognizer.self.view;
    if (!_isStarDrag) {
        return;
    }
    CGPoint translatedPoint = [recognizer translationInView:self];
    CGFloat x = recognizer.view.center.x + translatedPoint.x;
    CGFloat y = recognizer.view.center.y + translatedPoint.y;
    recognizer.view.center = CGPointMake(x, y);
    [recognizer setTranslation:CGPointMake(0, 0) inView:self];
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
        return YES;
}

// 返回当前拖动的图片是否已经进入另一个图片的范围内
- (BOOL)returnRectIsContainCGPoint:(CGRect)rect andPoint:(CGPoint)point {
    return CGRectContainsPoint(rect, point);
}

- (void)updateHeaderAndBackgroundColor:(int)which andDic:(NSDictionary *)dic {
    [self setWhichMuBanAndDic:which andDic:dic];
    oneMuBanDic = [dic objectForKey:[NSString stringWithFormat:@"%d", which]];
    
    if ([(NSString *)[oneMuBanDic objectForKey:@"hexColor"] length] <= 1) {
        [[self viewWithTag:11] removeFromSuperview];
        UIImage *image = [UIImage imageNamed:[oneMuBanDic objectForKey:@"backImage"]];
//        if (which == 3) {
//            backgroundImage = [[UIImageView alloc] initWithImage:image];
//            backgroundImage.tag = 11;
//            [self insertSubview:backgroundImage atIndex:0];
//            [self setBackgroundColor:[UIColor clearColor]];
//        } else {
            if (image.size.width > 250) {
                [self setBackgroundColor:[UIColor colorWithPatternImage:[image resizedImageWithContentMode:UIViewContentModeScaleAspectFit bounds:CGSizeMake(self.frame.size.width, self.frame.size.height) interpolationQuality:kCGInterpolationDefault]]];
            } else {
                //
            }
//        }
    } else {
        [backgroundImage removeFromSuperview];
        backgroundImage = nil;
        long test = strtoul([[NSString stringWithFormat:@"0x%@", [oneMuBanDic objectForKey:@"hexColor"]] UTF8String],0,0);
        [self setBackgroundColor:HexRGB(test)];
    }
    
    CGSize size = CGSizeZero;
    if (headerImageView == nil) {
        headerImageView = [[UIImageView alloc] init];
        UIImage *headerImage = [UIImage imageNamed:[oneMuBanDic objectForKey:@"headerImageName"]];
        size = [self returnNowSizeWithOriginSize:CGSizeMake(headerImage.size.width, headerImage.size.height) andWantWidth:self.frame.size.width];
        [headerImageView setImage:headerImage];
        [headerImageView setFrame:CGRectMake(0, 0, size.width, size.height)];
        [self addSubview:headerImageView];
    } else {
        UIImage *headerImage = [UIImage imageNamed:[oneMuBanDic objectForKey:@"headerImageName"]];
        size = [self returnNowSizeWithOriginSize:CGSizeMake(headerImage.size.width, headerImage.size.height) andWantWidth:self.frame.size.width];
        [headerImageView setImage:headerImage];
        [headerImageView setFrame:CGRectMake(0, 0, size.width, size.height)];
    }
    
    headerHeight = size.height;
    [allImageView setFrame:CGRectMake(0, headerHeight, self.frame.size.width, contentHeight)];
}

- (void)updateContentImage {
}

- (void)updateFooter:(int)which andDic:(NSDictionary *)dic {
    [self setWhichMuBanAndDic:which andDic:dic];
    if ([oneMuBanDic objectForKey:@"footerImageName"] == nil || [(NSString *)[oneMuBanDic objectForKey:@"footerImageName"] length] <=1) {
        if (footerImageView != nil) {
            [footerImageView removeFromSuperview];
            footerImageView = nil;
        }
        [self setContentSize:CGSizeMake(self.frame.size.width, headerHeight + contentHeight + 7)];
        return;
    }
    
    // 尾部
    CGSize size = CGSizeZero;
    if (footerImageView == nil) {
        footerImageView = [[UIImageView alloc] init];
        UIImage *footerImage = [UIImage imageNamed:[oneMuBanDic objectForKey:@"footerImageName"]];
        size = [self returnNowSizeWithOriginSize:CGSizeMake(footerImage.size.width, footerImage.size.height) andWantWidth:self.frame.size.width];
        [footerImageView setImage:footerImage];
        [footerImageView setFrame:CGRectMake(0, headerHeight + contentHeight, size.width, size.height)];
        [self addSubview:footerImageView];
    } else {
        UIImage *footerImage = [UIImage imageNamed:[oneMuBanDic objectForKey:@"footerImageName"]];
        size = [self returnNowSizeWithOriginSize:CGSizeMake(footerImage.size.width, footerImage.size.height) andWantWidth:self.frame.size.width];
        [footerImageView setImage:footerImage];
        [footerImageView setFrame:CGRectMake(0, headerHeight + contentHeight, size.width, size.height)];
    }
    
    footerHeight = size.height;
    [self setContentSize:CGSizeMake(self.frame.size.width, headerHeight + contentHeight + footerHeight)];
    [backgroundImage setFrame:CGRectMake(0, headerHeight, self.frame.size.width, contentHeight)];
}

- (void)setWhichMuBanAndDic:(int)which andDic:(NSDictionary *)dic {
    if (dicFromPrePage == nil) {
        dicFromPrePage = dic;
    }
    whichYangShi = which;
}

- (void)updateImageOrder:(int)which andDic:(NSDictionary *)dic {
}

- (CGSize)returnNowSizeWithOriginSize:(CGSize)originSize2 andWantWidth:(float)wantWidth {
    float scale = wantWidth / originSize2.width;
    return CGSizeMake(wantWidth, originSize2.height * scale);
}

- (NSString *)rectToString:(CGRect)frame {
    return [NSString stringWithFormat:@"%f,%f,%f,%f",frame.origin.x, frame.origin.y, frame.size.width, frame.size.height];
}

- (CGRect)stringToRect:(NSString *)str {
    NSArray *arr = [str componentsSeparatedByString:@","];
    return CGRectMake([[arr firstObject] floatValue], [[arr objectAtIndex:1] floatValue], [[arr objectAtIndex:2] floatValue], [[arr lastObject] floatValue]);
}
@end









